<?php
global $_W,$_GPC;
$op = empty($_GPC['op'])?'display':$_GPC['op'];
$weid = $_W['uniacid'];
if($op == 'display'){
	$pindex = max(intval($_GPC['page']), 1);
	$psize = 20;
	$condition = "";
	if(!empty($_GPC['keyword'])){
		$condition .= " and title like '%{$_GPC['keyword']}%' ";
	}
	$limit = "limit " . (($pindex -1) * $psize).','. $psize;
	$list = getall('select * from ' . tablename($this->modulename.'_act') . " where uniacid = '{$weid}' {$condition} order by id {$limit}");
	foreach ($list as &$v) {
		$v['total'] = col("select count(1) from ".tb('codes')." where aid='{$v['id']}'");
		$v['use'] = col("select count(1) from ".tb('codes')." where aid='{$v['id']}' and mid>0");
	}
	$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_act') . " where uniacid = '{$weid}' ");
	$pager = pagination($total, $pindex, $psize);
}
elseif($op == 'post'){
	$id = $_GPC['id'];
	if(!empty($id)){
		$item = pdo_fetch('select * from ' . tablename($this->modulename.'_act') . " where id = '{$id}'" );
	}
	if(checksubmit()){
		$data = array(
			'uniacid' => $_W['uniacid'],
			'title' => trim($_GPC['title']),
			'kword' => trim($_GPC['kword']),
			'kwtips' => htmlspecialchars_decode(str_replace('&quot;','&#039;',$_GPC ['kwtips']),ENT_QUOTES),
			'scoretips' => htmlspecialchars_decode(str_replace('&quot;','&#039;',$_GPC ['scoretips']),ENT_QUOTES),
			'nostarttips' => htmlspecialchars_decode(str_replace('&quot;','&#039;',$_GPC ['nostarttips']),ENT_QUOTES),
			'endtips' => htmlspecialchars_decode(str_replace('&quot;','&#039;',$_GPC ['endtips']),ENT_QUOTES),
			'starttime' => strtotime($_GPC['datelimit']['start']),
			'endtime' => strtotime($_GPC['datelimit']['end']),
		);
		if ($item){
			pdo_update($this->modulename.'_act',$data,array('id'=>$id));
		}else{
			pdo_insert($this->modulename.'_act',$data);
			$id = pdo_insertid();
		}
		
		if (empty($item) || $item['kword'] != $data['kword']){
			
			$rule = get("select id from ".tablename('rule')." where uniacid='{$_W['uniacid']}' and module='junsion_wxtools' and name='junsion_wxtools_act'");
			if (empty($rule)){
				$rule = array(
					'uniacid' => $_W['uniacid'],
					'name' => 'junsion_wxtools_act',
					'module' => $this->modulename,
					'status' => 1,
					'displayorder' => 254,
				);
				pdo_insert('rule',$rule);
				$rule['id'] = pdo_insertid();
			}
			$rk = pdo_fetch('select id from '.tablename('rule_keyword')." where rid='{$rule['id']}' and content='{$item['kword']}' limit 1");
			if (empty($rk)){
				$rulew = array(
					'uniacid' => $_W['uniacid'],
					'module' => $this->modulename,
					'status' => 1,
					'displayorder' => 254,
					'type'=>1,
					'rid'=>$rule['id'],
					'content'=>$data['kword'],
				);
				pdo_insert('rule_keyword',$rulew);
			}else pdo_update('rule_keyword',array('content'=>$data['kword']),array('id'=>$rk['id']));
		}
		
		$score = intval($_GPC['score']);
		set_time_limit(0);
		include IA_ROOT.'/addons/junsion_wxtools/excel/oleread.php';
		include IA_ROOT.'/addons/junsion_wxtools/excel/excel.php';
		$tmp = $_FILES['codes']['tmp_name'];
		if (!empty ($tmp)) {
			$file_name = date('Ymdhis') . ".xls"; //上传后的文件保存路径和名称
			if (copy($tmp, $file_name)) {
				$xls = new Spreadsheet_Excel_Reader();
				$xls->setOutputEncoding('utf-8');  //设置编码
				$xls->read($file_name);  //解析文件
				for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) {
					$data_values[] = $xls->sheets[0]['cells'][$i];
				}
			}
			if (!empty($data_values)){
				$cid = 0;
				$inert_sql = " INSERT INTO ".tb('codes')." (uniacid,aid,code,score) ";
				foreach ($data_values as $value) {
					if($value[1] == ''){
						continue;
					}
		
					if(!empty($insert_val)){
						$insert_val .= ", ";
					}
						
					$v = explode('|', $value[1]);
		
					$insert_val .= " ({$_W['uniacid']},{$id},'{$v[0]}','{$score}') ";
				}
				pdo_query($inert_sql." VALUES ".$insert_val);
			}
			@unlink($file_name);
		}
		message('操作成功',$this->createWebUrl('codescore'),'success');
	}
	if(empty($item['starttime'])){
		$item['starttime'] = TIMESTAMP;
		$item['endtime'] = TIMESTAMP + 7 * 86400;
	}
}
elseif ($op == 'delete') {
	$id = $_GPC['id'];
	$item = pdo_fetch('select * from ' . tablename($this->modulename.'_act') . " where id = '{$id}'");
	if(empty($item)){
		message('操作失败',$this->createWebUrl('codescore'),'error');
	}
	if(pdo_delete($this->modulename.'_act',array('id'=>$id)) === false) message('操作失败',referer(),'error');
	else message('操作成功',$this->createWebUrl('codescore'),'success');
}elseif($op == 'code'){
	$pindex = max(intval($_GPC['page']), 1);
	$psize = 20;
	$aid = intval($_GPC['aid']);
	$limit = "limit " . (($pindex -1) * $psize).','. $psize;
	$list = getall('select * from ' . tablename($this->modulename.'_codes') . " where aid = '{$aid}' order by usetime {$limit}");
	if ($list){
		foreach ($list as $value) {
			if ($value['mid']) $mids[] = $value['mid'];
		}
		if ($mids){
			$mems = getall("select id,nickname,avatar from ".tb('mem')." where id in (".implode(',', $mids).")",'id');
		}
	}
	$total = pdo_fetchcolumn('select count(1) from ' . tablename($this->modulename.'_codes') . " where aid = '{$aid}' ");
	$pager = pagination($total, $pindex, $psize);
}
include $this->template('codescore');
